#!/usr/bin/env python
#Copyright (c) 2011 Isaac Dawson (WBTS Project)
#Permission is hereby granted, free of charge, to any person obtaining a copy 
#of this software and associated documentation files (the "Software"), to deal 
#in the Software without restriction, including without limitation the rights 
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
#copies of the Software, and to permit persons to whom the Software is furnished
#to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
#THE SOFTWARE.
import os
from wbts.web.processors import *
# if already imported we'll get an attribute error.
try:
    from wbts.storage import *
except AttributeError:
    pass

def cb_print_error(msg):
    print msg

def is_id_valid(id_value):
    return is_port_valid(id_value)

def is_port_valid(port_value):
    if (port_value == None):
        return False
    try:
        port_value = int(port_value)
    except ValueError:
        return False
    except TypeError:
        return False
    
    if (port_value > 65535 or port_value < 1):
        return False
    return True

def is_file_valid(file_value):
    return is_path_valid(file_value)
    
def is_path_valid(path_value):
    if (path_value == None or not isinstance(path_value, str)):
        return False
    if (os.path.exists(path_value)):
        return True
    return False

def is_class_valid(string_value):
    """
    Basically we only care if the module is not resolvable (NameError) or the
    class is not found (AttributeError) all other errors we ignore and say
    Yes we found it. We also make sure we were passed a string.
        """
    if (string_value == None or
        not isinstance(string_value, str) or
        string_value == ''):
        return False
    try:
        #bleh.
        x = eval(string_value+"()")
    except NameError, msg:
        print "%s is an invalid module: %s"%(string_value,msg)
        return False
    except AttributeError, msg:
        print "%s class does not appear to be valid: %s"%(string_value,msg)
        return False
    except Exception:
        # Don't Care.
        pass
    
    return True
    